package com.szj.spushrtmp.push;

import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.view.SurfaceView;

import androidx.appcompat.app.AppCompatActivity;

import com.szj.spushrtmp.util.video.CameraHelper;
import com.szj.spushrtmp.util.SLog;

/**
 * @ClassName: VideoChannel
 * @Author: s10g
 * @CreateDate: 7/30/23$ 12:27 PM$
 * TODO
 */
public class VideoChannel implements Camera.PreviewCallback, CameraHelper.OnChangedSizeListener {


    private final AppCompatActivity activity;
    private final SurfaceView surfaceView;
    private final int width;
    private final int height;

    // 是否播放
    private boolean isPlay;

    // 每秒多少帧
    private final int FPS = 25;

    // 码率(比特率)
    private final int BITRATE = 800_000;

    // 摄像头辅助类
    private final CameraHelper cameraHelper;

    public VideoChannel(AppCompatActivity activity, SurfaceView surfaceView) {
        this.activity = activity;
        this.surfaceView = surfaceView;

        DisplayMetrics displayMetrics = getDisplayMetrics();
//        width = displayMetrics.widthPixels;
//        height = displayMetrics.heightPixels;
        width = 640;
        height = 480;

        cameraHelper = new CameraHelper(activity, 0, width, height);
        // 绑定SurfaceView
        cameraHelper.setPreviewDisplay(surfaceView.getHolder());

        cameraHelper.setPreviewCallback(this);
        cameraHelper.setOnChangedSizeListener(this);
    }


    public DisplayMetrics getDisplayMetrics() {
        return activity.getResources().getDisplayMetrics();
    }

    /*
     * 作者:s10g
     * 创建时间: 7/30/23 12:38 PM
     * TODO 切换摄像头 [前置 <--> 后置 ]
     */
    public void switchCamera() {
        cameraHelper.switchCamera();
    }


    public void startPlay() {
        isPlay = true;
    }

    public void stopPlay() {
        isPlay = false;
    }

    public void release() {
        cameraHelper.stopPreview();
    }

    // 宽高改变回调 (切换摄像头也会改变)
    @Override
    public void onChanged(int width, int height) {
        SLog.e("onChanged:oldWidth:" + this.width + "\toldHeight:" + this.height + "\tnewWidth:" + width + "\theight:" + height);
        native_video_changed(width, height, FPS, BITRATE);
    }

    // nv21数据回调
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (isPlay) { // 播放视频
            native_video_data(data);
        }
    }

    // 初始化X264编码器
    private native void native_video_changed(int width, int height, int fps, int bitrate);

    private native void native_video_data(byte[] data);
}
